<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Main extends CI_Controller {

    public $user_id;
    
    public function __construct() {
        parent::__construct();
        $this->load->library('session');
        $this->load->model('expenses');
        $this->load->helper('url');
        $this->user_id = $this->session->userdata('user_id');
    }
    
    public function check(){
        if($this->session->userdata('logged') == null){
            redirect('user/login');
        }
    }
    
    public function index(){
        $this->check();
        $data = array();
        $data['title'] = 'Home';
        $expenses = array();
        $expenses['this_month'] = $this->expenses->get_this_month();
        $expenses['last_item'] = $this->expenses->get_last_item();
        $data['content'] = $this->load->view('expense/home',$expenses,TRUE);
        $this->load->view('main',$data);
    }
    
    public function add(){
        $this->check();
        $data = array();
        $item = array();
        $data['title'] = 'Add';
        $item['cat'] = $this->expenses->get_category_by_user_id($this->user_id);
        $data['content'] = $this->load->view('expense/add',$item,TRUE);
        $this->load->view('main',$data);
    }
     
    public function add_post(){
        $this->check();
        $title = $this->input->post('title');
        $amount = $this->input->post('amount');
        $cat_id = $this->input->post('category');
        if(is_array($title)){
            $input = array();
            foreach ($title as $key => $value) {
                $input[$key]['title'] = trim($value);
                $input[$key]['amount'] = trim($amount[$key]);
                $input[$key]['category'] = trim($cat_id[$key]);
            }
        }
        $this->expenses->insert($input,is_array($title));
        $this->session->set_flashdata('add_status', TRUE);
        redirect('main');
    }
    
    function getjson($start){
        $exp = $this->expenses->get_limit($start,10);
        echo json_encode($exp->result());
    }
    
    function delete($id){
        echo $this->expenses->delete($id);
    }
}

?>